package com.hzsai.dynamicdatasource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * hzsai 2019/8/28
 * usage:
 **/
@Configuration
@MapperScan(basePackages = "com.hzsai.mappersc", sqlSessionFactoryRef = "sqlSessionFactory_e1")
public class DynamicDataSourceConfig {

    @Autowired
    @Qualifier(value = "springbootDS")
    private DataSource ds1;

    @Autowired
    @Qualifier(value = "sakilaDS")
    private DataSource ds2;

    @Autowired
    @Qualifier(value = "springbootDS_e1")
    private DataSource ds3;

    @Autowired
    @Qualifier(value = "sakilaDS_e1")
    private DataSource ds4;

    @Bean
    public DataSource dynamicDataSource() {
        // 实现了javax.sql.DataSource
        DynamicDataSourceRouting dataSourceRouting = new DynamicDataSourceRouting();
        Map<Object, Object> DSMap = new HashMap<>();
        DSMap.put(DataSourceKey.FIRST, ds1);
        DSMap.put(DataSourceKey.SECOND, ds2);
        DSMap.put(DataSourceKey.THIRD, ds3);
        DSMap.put(DataSourceKey.FOUTH, ds4);
        dataSourceRouting.setTargetDataSources(DSMap);
        return dataSourceRouting;
    }

    @Bean
    public SqlSessionFactory sqlSessionFactory_e1() throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dynamicDataSource());
        // 有可能找不到mapper
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper*/*.xml"));
        return bean.getObject();
    }

    @Bean
    public DataSourceTransactionManager manager() {
        return new DataSourceTransactionManager(dynamicDataSource());
    }

    @Bean
    public SqlSessionTemplate template() throws Exception {
        SqlSessionTemplate template = new SqlSessionTemplate(sqlSessionFactory_e1());
        return template;
    }
}
